#include <key.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "device.h"
#include "console.h"

static void dump_hex(char * title, uint8_t * buf, int len)
{
        int i;
        printf(title);
        printf(":");
        for (i = 0; i < len; i ++) printf("%02x", buf[i]);
        printf("\n");
}

static void command_picc(int argc, const char **argv)
{
       uint8_t *p, i;
       icc_ex_t ex;

        if (argc == 1) {
                printf("PICC Random Test:\n");
                if (icc_present(4)) {
                        icc_powerup(&ex);
                        if (ex.resp == 0) {
                                p = ex.exbuf;
                                printf("Type:%c, UID:", *p++);
                                for (i=*p++; i>0; i--) printf("%02x", *p++);   
                                printf(", ATR:");
                                for (i=*p++; i>0; i--) printf("%02x", *p++);
                                printf("\n");
                                memcpy(ex.exbuf, "\x00\x84\x00\x00\x08", 5);
                                ex.inlen = 5;
                                icc_apdu(&ex);
                                if (ex.resp > 0) dump_hex("Random", ex.exbuf, ex.resp);
                                else printf("ICC APDU Failed:%d\n", ex.resp);
                                //icc_powerdown();
                        }
                        else {
                                printf("Power Up Failed:%d\n", ex.resp);
                        }
                }
                icc_powerdown();
        }

}

const command_t picc_cmd __command_entry = {
    "picc",
    command_picc,
    "picc -- Proximity IC Card Test"
};
